<template>
    <el-dialog
        :title="!dataForm.id ? $t('handle.add') : show? $t('handle.update') : $t('handle.detail')"
        :close-on-click-modal="false"
        :visible.sync="visible">
    <div v-loading = loading>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="100px">
      <el-form-item v-if="superAdmin==1" label="所属小区" prop="housingEstateId">
         <el-cascader ref="cascader" clearable style="width: 100%;" v-model="address" :options="options"  @click.native="getOne" @active-item-change="getNodes" :show-all-levels="true" :props="props">
         </el-cascader>
      </el-form-item>
      <el-form-item :label="$t('common.title')" prop="title">
        <el-input v-model="dataForm.title"
         placeholder="标题"></el-input>
      </el-form-item>
      <el-form-item label="摘要" prop="subTitle">
        <el-input v-model="dataForm.subTitle" :max = "100"
         placeholder="摘要"></el-input>
      </el-form-item>
      <el-form-item label="发布人" prop="author">
        <el-input v-model="dataForm.author" placeholder="发布人" ></el-input>
      </el-form-item>
      <el-form-item label="原文作者" prop="originalAuthor">
        <el-input v-model="dataForm.originalAuthor" placeholder="原文作者" ></el-input>
      </el-form-item>
      <el-form-item label="原文地址" prop="originalUrl">
        <el-input v-model="dataForm.originalUrl" placeholder="原文地址" ></el-input>
      </el-form-item>
      <el-form-item v-if="false" label="完成标识" prop="completeFlag">
        <el-input v-model="dataForm.completeFlag" placeholder="完成标识" ></el-input>
      </el-form-item>
      <el-form-item label="发布时间" prop="publishDate">
        <el-col :span="11">
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="dataForm.publishDate"
            style="width: 100%;"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions0"
          ></el-date-picker>
        </el-col>
        <el-col :span="12">
          <!-- <el-time-picker placeholder="选择时间" v-model="date2" style="width: 100%;" value-format="HH:mm:ss"></el-time-picker> -->
          <el-form-item :label="$t('status.status')" prop="status">
            <el-select style="width: 111%;" v-model="dataForm.status" filterable placeholder="请选择">
              <el-option v-for="item in dicts" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-form-item>
      <span ></span>
      <!-- <el-form-item :label="$t('status.status')" prop="status">
          <el-select style="width: 100%;" v-model="dataForm.status" filterable placeholder="请选择">
            <el-option v-for="item in dicts" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
      </el-form-item> -->
      <el-form-item label="宣传详情" prop="content">
        <ueditor :content="dataForm.content" v-if="true" ref="ueditor" @ueditorContent="getUeditorContent"> </ueditor>
        <!-- <el-color-picker v-model="dataForm.contentColor"></el-color-picker>

        <el-input type="textarea"
        :rows="10"
        :maxlength = "500"
        v-model="dataForm.content" placeholder="宣传详情(最长500字符)"></el-input> -->
      </el-form-item>
    </el-form>
    <div style="text-align:right;">
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('handle.cancel') }}</el-button>
      <el-button v-if="show" type="primary" @click="dataFormSubmit()">{{ $t('handle.confirm') }}</el-button>
    </span>
    </div>
    </div>
  </el-dialog>
</template>
<script>
import ueditor from "./ueditor";
import { dateFormate } from "@/utils/validate";
import { imgUrlHost } from "@/config/env";
import {
  getOne,
  getTwo,
  getThree,
  getFour,
  getFive,
  getSix
} from "@/utils/questUtils";
export default {
  data() {
    // 严格的验证规则可以放到这里验证
    let checkHousingEstate = (rule, value, callback) => {
      if (typeof this.address[this.address.length - 1] === "undefined") {
        callback(new Error("小区不能为空"));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      imgUrlHost: imgUrlHost,
      superAdmin: sessionStorage.getItem("superAdmin"),
      options: [{}],
      props: {
        value: "id",
        label: "name",
        children: "children"
      },
      address: [],
      date1: "",
      date2: "",
      dicts: [],
      show: true,
      visible: false,
      dataForm: {
        id: "",
        title: "",
        subTitle: "",
        status: "",
        author: "",
        content: "",
        publishDate: "",
        originalAuthor: "",
        originalUrl: ""

        // contentColor:''
      },
      // 验证Todo 其他的验证后续加上
      dataRule: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" },
          { max: 50, message: "最大长度为50字符", trigger: "blur" }
        ],
        author: [{ required: true, message: "作者不能为空", trigger: "blur" }],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        publishDate: [{ required: true, message: "时间不能为空", trigger: "blur" }],
        subTitle: [{ max: 100, message: "最大长度为100字符", trigger: "blur" }],
        housingEstateId: [
          { required: true, validator: checkHousingEstate, trigger: "blur" }
        ]
      },
      pickerOptions0: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      }
    };
  },
  mounted() {},
  // 引入的组件
  components: {
    ueditor
  },
  methods: {
    // 一级
    getOne() {
      getOne().then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options = response.data.page;
        }
      });
    },
    // 二级
    getTwo(countryId) {
      getTwo(countryId).then(response => {
        if (response.data.page && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map(item => {
            if (item.id === countryId) {
              item.children = response.data.page;
            }
          });
        }
      });
    },
    getThree(countryId, provinceId) {
      getThree(provinceId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((city, id) => {
                city.children = response.data.page;
              });
            }
          });
        }
      });
    },
    getFour(countryId, provinceId, cityId) {
      getFour(cityId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    city.children = response.data.page;
                  });
                }
              });
            }
          });
        }
      });
    },
    getFive(countryId, provinceId, cityId, areaId) {
      getFive(areaId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        area.children = response.data.page;
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    getSix(countryId, provinceId, cityId, areaId, communityCodeId) {
      getSix(communityCodeId).then(response => {
        if (response.data && response.data.code === 0) {
          response.data.page.map(item => {
            this.$set(item, "name", item.name);
            // this.$set(item, "children", []);
          });
          this.options.map((item, i) => {
            if (item.id === countryId) {
              item.children.map((provice, idx) => {
                if (provice.id === provinceId) {
                  provice.children.map((city, ids) => {
                    if (city.id === cityId) {
                      city.children.map((area, aid) => {
                        if (area.id === areaId) {
                          area.children.map((communt, ic) => {
                            communt.children = response.data.page;
                          });
                        }
                      });
                    }
                  });
                }
              });
            }
          });
        }
      });
    },
    getNodes(val) {
      if (val.length === 1) {
        // 获取省
        this.getTwo(val[0]);
      } else if (val.length === 2) {
        // 市
        this.getThree(val[0], val[1]);
      } else if (val.length === 3) {
        // 区
        this.getFour(val[0], val[1], val[2]);
      } else if (val.length === 4) {
        this.getFive(val[0], val[1], val[2], val[3]); //社区
      } else if (val.length === 5) {
        this.getSix(val[0], val[1], val[2], val[3], val[4]); // 小区
      }
      //如果继续添加下级，类似这样继续添加即可
    },
    getUeditorContent(msg) {
      // this.dataForm.completeFlag = msg[0]
      this.dataForm.content = msg;
    },
    clearForm() {
      this.address = [];
      this.dataForm.title = "";
      this.dataForm.subTitle = "";
      this.dataForm.author = "";
      this.dataForm.status = "";
      this.dataForm.content = "";
      this.dataForm.publishDate = "";
      this.date1 = "";
      this.date2 = "";
      this.dataForm.originalAuthor = "";
      this.dataForm.originalUrl = "";
    },
    init(id, show, dicts) {
      this.dicts = dicts;
      this.show = show;
      this.visible = true;
      this.dataForm.id = id || 0;
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields();
      });
      if (typeof id == "undefined") {
        // 新增
        this.clearForm();
      }
      if (this.dataForm.id) {
        this.$http({
          url: `/dg-ic/ic/community-publicity/info/${this.dataForm.id}`,
          method: "get",
          params: this.$http.adornParams()
        }).then(
          ({ data }) => {
            if (data && data.code === 0) {
              this.dataForm.title = data.data.title;
              this.dataForm.subTitle = data.data.subTitle;
              this.dataForm.author = data.data.author;
              this.dataForm.status = String(data.data.status);
              this.dataForm.content = data.data.content;
              this.dataForm.publishDate = data.data.publishDate;
              this.date1 = data.data.publishDate;
              this.date2 = dateFormate(
                data.data.publishDate,
                this.date1,
                this.date2
              );
              this.dataForm.originalAuthor = data.data.originalAuthor;
              this.dataForm.originalUrl = data.data.originalUrl;
              this.options = [
                {
                  id: data.data.housingEstateId,
                  name: data.data.housingEstateName
                }
              ];
              this.address = [data.data.housingEstateId];
              // this.contentColor = this.data.contentColor
            } else {
              this.$message.error(data.msg);
            }
          },
          error => {
            if (error.response.status === 403) {
              this.$message.error("你没有权限");
            } else {
              this.$message.error("系统错误，请联系管理员");
            }
          }
        );
      }
    },
    // 表单提交
    dataFormSubmit() {
      // console.log(this.date2.toString().substr(16,8))
      this.$refs["dataForm"].validate(validate => {
        if (validate) {
          this.loading = true;
          this.$http({
            url: `/dg-ic/ic/community-publicity/${
              !this.dataForm.id ? "save" : "update"
            }`,
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              title: this.dataForm.title,
              subTitle: this.dataForm.subTitle,
              author: this.dataForm.author,
              status: this.dataForm.status,
              content: this.dataForm.content,
              housingEstateId:
                sessionStorage.getItem("superAdmin") == 1
                  ? this.address[this.address.length - 1]
                  : sessionStorage.getItem("thiscommunityId"), // 看是不是超管，时的话就给小区选择，否则就给他自身带的小区id
              createBy: this.$store.state.user.id,
              updateBy: this.$store.state.user.id,
              // 'publishDateS':this.date1?(typeof(this.date2)==='string'?this.date1.substr(0,10) +' '+ this.date2:this.date1 + ' '+  this.date2?'':this.data2.substr(16,8)):this.date2,
              publishDateS: this.dataForm.publishDate ? this.dataForm.publishDate.substr(0, 10) : "",
              originalAuthor: this.dataForm.originalAuthor,
              originalUrl: this.dataForm.originalUrl
              // 'contentColor':this.dataForm.contentColor
              // 后续的字段后续加上
            })
          }).then(
            ({ data }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.loading = false;
                    this.visible = false;
                    this.$emit("refreshDataList");
                  }
                });
              } else {
                this.$message.error(data.msg);
                this.loading = false;
              }
            },
            error => {
              if (error.response.status === 403) {
                this.$message.error("你没有权限");
                this.loading = false;
              } else {
                this.$message.error("系统错误，请联系管理员");
                this.loading = false;
              }
            }
          );
        }
      });
    }
  }
};
</script>
